﻿using Dapper;
using Microsoft.Data.Sqlite;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;

namespace AssetServiceHost
{
    public class SystemDBContext : IDisposable, JMS.IStorageEngine
    {
        static SystemDBContext()
        {
            //创建表
            using var con = CreateConnection();
            con.Open();

            con.Execute(@"
CREATE TABLE IF NOT EXISTS MoneyAccount (  
    Id INTEGER PRIMARY KEY AUTOINCREMENT,   
    UserId INTEGER UNIQUE,  
    Balance REAL
);
");

        }

        static SqliteConnection CreateConnection()
        {
            return new SqliteConnection("data source='data.db'");
        }

        public event EventHandler AfterCommit;
        public event EventHandler AfterRollback;
        public SqliteConnection Connection { get; }
        public SystemDBContext()
        {
            Connection = CreateConnection();
            Connection.Open();
        }

        /// <summary>
        /// 当前事务对象
        /// </summary>
        public object CurrentTransaction { get; set; }

        public void BeginTransaction()
        {
            if (this.CurrentTransaction == null)
            {
                this.CurrentTransaction = this.Connection.BeginTransaction();
            }

        }
        public void CommitTransaction()
        {
            if (this.CurrentTransaction != null)
            {
                ((SqliteTransaction)this.CurrentTransaction).Commit();
                ((SqliteTransaction)this.CurrentTransaction).Dispose();
                this.CurrentTransaction = null;

                AfterCommit?.Invoke(this, EventArgs.Empty);
            }

        }
        public void RollbackTransaction()
        {
            if (this.CurrentTransaction != null)
            {
                ((SqliteTransaction)this.CurrentTransaction).Rollback();
                ((SqliteTransaction)this.CurrentTransaction).Dispose();
                this.CurrentTransaction = null;

                AfterRollback?.Invoke(this, EventArgs.Empty);
            }
        }

        public void Dispose()
        {
            if (this.CurrentTransaction != null)
            {
                RollbackTransaction();
            }
            this.CurrentTransaction = null;

            Connection.Dispose();
        }
    }
}
